package com.ljx.funchat.common.event.listener;

import com.ljx.funchat.chat.dao.MessageDao;
import com.ljx.funchat.chat.dao.RedbagDao;
import com.ljx.funchat.chat.domain.entity.Redbag;
import com.ljx.funchat.common.constant.RedisKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis过期监听
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedbagDao redbagDao;

    @Autowired
    private MessageDao messageDao;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message 失效的key
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = message.toString();
        log.info("过期redis数据key：" + key);
        if (key.contains("redbagValid")){
            // 红包过期事件
            handleRedbagInvalid(key);
        }

    }

    private void handleRedbagInvalid(String key) {
        // 更新红包状态
        Long redbagId = Long.parseLong(key.replace("redbagValid:id_", ""));
        Redbag redbag = redbagDao.getById(redbagId);
        messageDao.updateRedbagInvalidById(redbag.getMessageId());
        // TODO 返回余额
    }
}
